package userAPI

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go-gin-init/app/core"
	"go-gin-init/app/models/req"
	"go-gin-init/app/models/resp"
	"go-gin-init/app/service"
	"go-gin-init/common/result"
	"go-gin-init/common/tool"
	"go-gin-init/common/xerr"
	"go.uber.org/zap"
)

// UserLogin
// @Summary 用户登入
// @Description
// @Tags USER
// @Accept json
// @Produce json
// @Param Param body req.UserLoginReq true "请求参数"
// @Success 200 {object} result.JsonResult "{"code":200,"data":{},"msg":"SUCCESS"}"
// @Failure 400 {object} result.JsonResult "{"code":200,"data":{},"msg":""}"
// @Failure 500 {string} string "Internal Server Error"
// @Router /user/login [post]
func UserLogin(c *gin.Context) {
	var u req.UserLoginReq

	if err := c.ShouldBind(&u); err != nil {
		result.ParamErrorResult(c, err)
		return
	}

	defaultUserModel := service.NewDefaultUserModel()

	loginUser, err := defaultUserModel.FindByUserName(u.UserName)

	if err != nil && !errors.Is(err, service.ErrNotFound) {
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		return
	}

	if loginUser == nil {
		result.JsonRsp(c, nil, xerr.NewErrMsg("用户不存在"))
		return
	}

	if loginUser.Password != u.Password {
		result.JsonRsp(c, nil, xerr.NewErrMsg("密码错误"))
		return
	}

	j := &tool.JWT{SigningKey: []byte(core.Conf.Server.SigningKey)} // 唯一签名
	claims := j.CreateClaims(resp.BaseClaims{
		ID:       loginUser.Id,
		Username: loginUser.UserName,
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		zap.L().Error("token 签发失败", zap.Error(err))
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.TOKEN_FAIL_CREATE))
		return
	}

	result.JsonRsp(c, resp.UserLoginResp{
		Id:          loginUser.Id,
		Username:    loginUser.UserName,
		Token:       token,
		TokenExpire: core.Conf.JWTAuth.AccessExpire,
	}, nil)

}
